package com.example.bootdemo.util;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.bootdemo.vo.PartyFeeRecord;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;


public class ExcelExportUtil {
    public static void main(String[] args) {
        List<PartyFeeRecord> records = generateSampleData(); // 生成示例数据
        exportToExcel(records, "C:/tmp/党费导出.xlsx");
    }

    public static void exportToExcel(List<PartyFeeRecord> records, String filePath) {
        // 创建 ExcelWriter
        ExcelWriter writer = ExcelUtil.getWriter(true);

        // 设置标题
        writer.addHeaderAlias("name", "姓名");
        writer.addHeaderAlias("orgName", "组织名称");
        writer.addHeaderAlias("year", "缴纳年份");
        writer.addHeaderAlias("month", "月份");
        writer.addHeaderAlias("amountDue", "应交金额");
        writer.addHeaderAlias("amountPaid", "实缴金额");
        writer.addHeaderAlias("percentage", "缴纳百分比");

        // 写入数据
        writer.write(records, true);

        // 合并单元格 (假设数据已按姓名、组织名称、缴纳年份排序)
        int rowIndex = 1; // 第一行是标题
        for (int i = 0; i < records.size(); i += 3) {
            if (i + 2 < records.size()) {
                writer.merge(rowIndex, rowIndex + 2, 0, 0, null, false); // 姓名
                writer.merge(rowIndex, rowIndex + 2, 1, 1, null, false); // 组织名称
                writer.merge(rowIndex, rowIndex + 2, 2, 2, null, false); // 缴纳年份
            }
            rowIndex += 3;
        }

        // 适应列宽
        writer.autoSizeColumnAll();

        // **正确的写入方式**
        try (OutputStream out = new FileOutputStream(filePath)) {
            writer.flush(out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            writer.close(); // 确保 writer 关闭，避免损坏文件
        }

        System.out.println("Excel 导出成功！文件路径: " + filePath);
    }

    private static List<PartyFeeRecord> generateSampleData() {
        List<PartyFeeRecord> list = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            PartyFeeRecord r1 = new PartyFeeRecord("张三", "组织A", 2024, "1月", 100.0, 100.0, 100.0);
            PartyFeeRecord r2 = new PartyFeeRecord("张三", "组织A", 2024, "2月", 120.0, 110.0, 91.67);
            PartyFeeRecord r3 = new PartyFeeRecord("张三", "组织A", 2024, "3月", 150.0, 150.0, 100.0);
            list.add(r1);
            list.add(r2);
            list.add(r3);
        }
        return list;
    }
}
